package com.jiaozi.base.utils;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import org.slf4j.MDC;

/**
 * 日志工具类
 */
public class LogUtil {
    private LogUtil(){}

    /**
     * trace id
     */
    private static final String TRACE_ID = "TRACE_ID";

    private static final String LOG_PREFIX = "LOG_PREFIX";

    private static final String UPDATE_TOKEN = "UPDATE_TOKEN";

    /**
     * 设置 TOKEN
     * TOKEN临济过期设置
     */
    public static void setToken(String token ) {
        MDC.put(UPDATE_TOKEN, token);
    }


    /**
     * 获取TOKEN
     * @return
     */
    public static String  getToken() {
        String token=MDC.get(UPDATE_TOKEN);
        if(StrUtil.isNotBlank(token)){
            return token;
        }
        return null;
    }



    /**
     * 设置 LogPrefix
     * @param LogPrefix LogPrefix
     */
    public static void setLogPrefix(final String LogPrefix) {
        MDC.put(LOG_PREFIX, StrUtil.isNotBlank(LogPrefix)?"["+LogPrefix+"]":"");
    }

    /**
     * 移除 LogPrefix
     */
    public static void removeLogPrefix() {
        MDC.remove(LOG_PREFIX);
    }

    /**
     * 获取日志前缀
     * @return 日志前缀
     */
    public static String getLogPrefix() {

        String LogPrefix=MDC.get(LOG_PREFIX);
        if(StrUtil.isNotBlank(LogPrefix)){
            return LogPrefix.replaceAll("^[\\[]+|[\\]]+$","");

        }else{
            return "";
        }
    }


    /**
     * 设置 traceId
     */
    public static String setTraceId( ) {
        String traceId=fastSimpleUUID();
        MDC.put(TRACE_ID, StrUtil.isNotBlank(traceId)?"["+traceId+"]":"");
        return traceId;
    }

    public static String setTraceId(final String traceId) {
        MDC.put(TRACE_ID, StrUtil.isNotBlank(traceId)?"["+traceId+"]":"");
        return traceId;
    }

    public static String setTraceId(final String traceId,final String sign) {
        String traceIdnew=StrUtil.isNotBlank(traceId)?"["+traceId+sign.toUpperCase()+"]":"";
        MDC.put(TRACE_ID, traceIdnew);
        return traceIdnew;
    }


    /**
     * 获取一个不带- 的uuid 截取前10位，并且转小写
     * @return
     */
    public static String fastSimpleUUID(){
        return UUID.fastUUID().toString(true).substring(10).toLowerCase();
    }

    /**
     * 移除 traceId
     */
    public static void removeTraceId() {
        MDC.remove(TRACE_ID);
    }

    /**
     * 移除 MDC
     */
    public static void clear() {
        removeTraceId();
        removeLogPrefix();

    }

    /**
     * 获取批次号
     * @return 批次号
     */
    public static String getTraceId() {
        String traceId=MDC.get(TRACE_ID);
        if(StrUtil.isNotBlank(traceId)){
            return traceId.replaceAll("^[\\[]+|[\\]]+$","");

        }else{
            return "";
        }
    }

}
